// src/router/routeIndex.js
import {createRouter, createWebHistory} from 'vue-router'
import {useUserStore} from "@/stores/modules/user.js";
import {getComponent} from "@/router/util/componentLoader.js";
import {getSystemMenu} from "@/api/commonService.js";

// 静态基础路由
const constantRoutes = [
    {
        path: '/',
        redirect: '/home'
    }, {
        path: '/login',
        component: () => import('@/views/login/LoginView.vue')
    }, {
        path: '/home',
        name: 'home',
        meta: {
            title: '首页',
        },
        component: () => import('@/views/home/AdminHome.vue'),
        children: [] // 动态路由将在这里添加
    }, {
        path: '/business/drugList',
        name: 'drugList',
        component: () => import('@/views/business/home-drug-list.vue')
    }
]

const router = createRouter({
    history: createWebHistory(import.meta.env.BASE_URL),
    routes: constantRoutes
})

// 动态添加路由的方法
export const addDynamicRoutes = async () => {
    try {
        // 从后端获取导航数据
        const response = await getSystemMenu()
        const routes = generateRoutes(response.data)
        // 动态添加到home路由下
        routes.forEach(route => {
            router.addRoute('home', route)
        })
        console.log('最终路由表：', router.getRoutes().map(route => route.path))
        return true
    } catch (error) {
        console.error('获取动态路由失败:', error)
        return false
    }
}

// 生成路由配置
const generateRoutes = (navigations) => {
    return navigations.map(item => {
        const route = {
            path: item.routePath,
            name: item.name,
            meta: {
                title: item.menuName,
                icon: item.icon,
                formCode: item.formCode
            },
            // 可以正常渲染路由
            component: () => Promise.resolve(getComponent(`${item.component}`))
        }

        // 如果有子路由则递归处理
        if (item.children && item.children.length > 0) {
            route.children = generateRoutes(item.children)
        }

        return route
    })
}

// 路由守卫中加载动态路由
router.beforeEach(async (to, from, next) => {
    const useStore = useUserStore()

    // 定义不需要登录的白名单路由
    const whiteList = ['/login', '/business/drugList']

    // 如果是白名单中的路由，直接放行
    if (whiteList.includes(to.path)) {
        return next()
    }

    // 已登录且未加载动态路由时加载
    if (useStore.token && !router.hasRoute('dynamicLoaded')) {
        await addDynamicRoutes()
        // 添加一个标记路由表示已加载
        router.addRoute('home', {
            path: '/dynamic-loaded',
            name: 'dynamicLoaded',
            component: {render: () => null}
        })
        // 重新导航到目标路由
        return next({...to, replace: true})
    }

    // 未登录处理
    if (!useStore.token) {
        return next('/login')
    }

    next()
})

export default router
